package com.jinzhi.jzweb.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.service.DictService;
import com.jinzhi.common.type.EnumErrorCode;
import com.jinzhi.common.utils.EhCacheUtil;
import com.jinzhi.common.utils.Result;
import com.jinzhi.common.utils.StringUtil;
import com.jinzhi.jzapi.msg.WxPushServiceQcl;
import com.jinzhi.jzweb.domain.ExaminationBatchComDO;
import com.jinzhi.jzweb.domain.ExaminationBatchComSDO;
import com.jinzhi.jzweb.domain.ExaminationBatchDO;
import com.jinzhi.jzweb.domain.StuSignUpComDO;
import com.jinzhi.jzweb.pojo.*;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.jzweb.utils.EasyPoiUtil;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.UserRoleService;
import com.jinzhi.sys.service.UserService;
import com.jinzhi.wxmp.service.MpConfigService;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 
 * <pre>
 * 考生报名   第一次加密
 * </pre>
 * <small> 2023-05-05 08:52:02 | lance</small>
 */
@Controller
@RequestMapping("/jzweb/stuSignUpComPo")
public class StuSignUpComPoController extends BaseController {
	@Autowired
	private StuSignUpComService stuSignUpComService;

	@Autowired
	private StuSignUpComService stuSignUpService;
	@Autowired
	private ExaminationBatchComService examinationBatchService;
	@Autowired
	private ExaminationAnswerSheetComService examinationAnswerSheetService;
	@Autowired
	private ExaminationBatchComSService comSService;

	@Autowired
	private ExaminationBatchComSService examinationBatchComServices;

	@Log("考生重考报名")
	@PostMapping("/reExam")
	@ResponseBody
	@RequiresPermissions("jzweb:stuSignUpCom:reExam")
	public Result<String> reExam(Long id) {
		StuSignUpComDO s = stuSignUpService.selectById(id);
		s.setState(8);//将考试转态“已考完”更改为“考试中”
		stuSignUpService.updateById(s);
		Map map = new HashMap<String,String>();
		map.put("stu_sign_id", id);
		examinationAnswerSheetService.deleteByMap(map);
		return Result.ok("操作成功！");
	}


	@GetMapping()
	@RequiresPermissions("jzweb:stuSignUpCom:stuSignUpCom")
	String StuSignUpCom(Integer types,Model model){
		model.addAttribute("types",types);
	    return "jzweb/stuSignUpCom/stuSignUpComPo";
	}



	@GetMapping("/stuSignUpComNum2")
	@RequiresPermissions("jzweb:stuSignUpCom:stuSignUpComNum2")
	String stuSignUpComNum2(Integer types,Model model){
		model.addAttribute("types",types);
		return "jzweb/stuSignUpCom/stuSignUpComNum2";
	}


	/**
	 * 赛场录入
	 * @param id
	 * @param model
	 * @return
	 */
	@GetMapping("/stuSignUpComEnter/{id}")
	@RequiresPermissions("jzweb:stuSignUpCom:resetPwd")
	String stuSignUpComEnter(@PathVariable("id") Long id,Model model){
	StuSignUpComDO stuSignUpComDO=	stuSignUpService.selectById(id);

		List <ExaminationBatchComSDO> list=comSService.findByKv("cbatch_id",stuSignUpComDO.getCbatchId());

		model.addAttribute("list",list);
		model.addAttribute("stuSignUpCom",stuSignUpComDO);
		return "jzweb/stuSignUpCom/enterPo";
	}

	/**
	 * 导如模板 信息
	 * @throws Exception
	 */
	@GetMapping("/exportList")
	@ResponseBody
	public void exportlist( HttpServletRequest request, HttpServletResponse responseexa) throws Exception{

		List<StuSignUpComVos> list = new LinkedList<>();
		//导出操作
		EasyPoiUtil.exportExcel(list, "选手导入模板", "选手导入模板", StuSignUpComVos.class, "选手导入模板", responseexa);

	}

	/**
     * 实操选手信息导出
     *
     * @param response
     */
	@GetMapping("/downloadImportStu")
	@RequiresPermissions("jzweb:stuSignUpCom:import")
	@ResponseBody
	public Result<String> downloadImportTemplate(HttpServletResponse response,StuSignUpComDO stuSignUpComDTO) {
		Result result = new Result();
		try {
			List<StuSignUpComVo> list1 = new LinkedList<>();
			Wrapper<StuSignUpComDO> wrapper = new EntityWrapper<StuSignUpComDO>().
					orderBy("comNum", true);
			if(StringUtils.isNotBlank(stuSignUpComDTO.getCbatchName())){
				wrapper.eq("cbatch_id",stuSignUpComDTO.getCbatchName());
			}
	/*		if(StringUtil.notEmpty(stuSignUpComDTO.getCompetitionType())){
				wrapper.addFilter("{0} like CONCAT('%',competition_type,'%')", stuSignUpComDTO.getCompetitionType());
			}*/
			if(StringUtil.notEmpty(stuSignUpComDTO.getIdNumber())){
				wrapper.like("id_number", stuSignUpComDTO.getIdNumber());
			}
			if(StringUtil.notEmpty(stuSignUpComDTO.getName())){
				wrapper.like("name", stuSignUpComDTO.getName());
			}
			List<StuSignUpComDO> list=	stuSignUpComService.selectList(wrapper);
			for(StuSignUpComDO li:list){
				StuSignUpComVo stuSignUpComVo=new StuSignUpComVo();
				BeanUtils.copyProperties(li,stuSignUpComVo);
				stuSignUpComVo.setName(li.getName());
				stuSignUpComVo.setIdNumber(li.getIdNumber());
				stuSignUpComVo.setTicketNumber(li.getTicketNumber());
				stuSignUpComVo.setNotes(li.getNotes());
				stuSignUpComVo.setUnitName(li.getUnitName());
				stuSignUpComVo.setSignUpTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(li.getSignUpTime()));
				/*if (li.getCompetitionType() != null){//idNumber
					List<ExaminationBatchComDO> examinationBatchComDO1 = examinationBatchService.selectType(li.getCompetitionType());
					if (examinationBatchComDO1.size() > 0){
						stuSignUpComVo.setCompetitionType(examinationBatchComDO1.get(0).getName());
					}
				}*/
				stuSignUpComVo.setCompetitionType(examinationBatchService.selectById(stuSignUpComDTO.getCbatchName()).getName());
			/*	if (li.getCourt2() != null){
					ExaminationBatchComSDO examinationBatchComSDO = examinationBatchComServices.selectById(li.getCourt2());
					if(examinationBatchComSDO!=null){
						stuSignUpComVo.setCourt(examinationBatchComSDO.getName());
					}
				}*/
				stuSignUpComVo.setTeacherName(li.getTeacher());
				stuSignUpComVo.setNum1(li.getRealityNm1());
				stuSignUpComVo.setNum2(li.getRealityNm2());
				stuSignUpComVo.setFamily(li.getFamily());
				stuSignUpComVo.setProvince(li.getProvince());
				if(li.getSex()==1){
					stuSignUpComVo.setSex("男");
				}else if(li.getSex()==2){
					stuSignUpComVo.setSex("女");
				}else{
					stuSignUpComVo.setSex("未知");
				}
				list1.add(stuSignUpComVo);
			}

			//导出操作
			EasyPoiUtil.exportExcel(list1, "考生报名信息导出", "考生报名信息导出", StuSignUpComVo.class, "考生报名信息导出", response);
		}catch (Exception e){
			e.printStackTrace();
			return result.fail();
		}
		return result.ok();
	}



	/**
	 * 赛道抽签导出
	 *
	 * @param response
	 */
	@GetMapping("/drawlots")
	//@RequiresPermissions("jzweb:stuSignUpCom:import")
	@ResponseBody
	public Result<String> drawlots(HttpServletResponse response,StuSignUpComDO stuSignUpComDTO) {
		Result result = new Result();
		try {
			List<DrawLotsVo> list1 = new LinkedList<>();
			Wrapper<StuSignUpComDO> wrapper = new EntityWrapper<StuSignUpComDO>().
					orderBy("comNum", true);
			if(StringUtils.isNotBlank(stuSignUpComDTO.getCbatchName())){
				wrapper.eq("cbatch_id",stuSignUpComDTO.getCbatchName());
			}
	/*		if(StringUtil.notEmpty(stuSignUpComDTO.getCompetitionType())){
				wrapper.addFilter("{0} like CONCAT('%',competition_type,'%')", stuSignUpComDTO.getCompetitionType());
			}*/
			if(StringUtil.notEmpty(stuSignUpComDTO.getIdNumber())){
				wrapper.like("id_number", stuSignUpComDTO.getIdNumber());
			}
			if(StringUtil.notEmpty(stuSignUpComDTO.getName())){
				wrapper.like("name", stuSignUpComDTO.getName());
			}
			wrapper.isNotNull("court2").ne("court2","");
			List<StuSignUpComDO> list=	stuSignUpComService.selectList(wrapper);
			for(StuSignUpComDO li:list){
				DrawLotsVo stuSignUpComVo=new DrawLotsVo();
				stuSignUpComVo.setName(li.getName());
				stuSignUpComVo.setUnitName(li.getUnitName());
				stuSignUpComVo.setSignUpTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(li.getSignUpTime()));
				/*if (li.getCompetitionType() != null){//idNumber
					List<ExaminationBatchComDO> examinationBatchComDO1 = examinationBatchService.selectType(li.getCompetitionType());
					if (examinationBatchComDO1.size() > 0){
						stuSignUpComVo.setCompetitionType(examinationBatchComDO1.get(0).getName());
					}
				}*/
				if (li.getCourt2() != null){
					ExaminationBatchComSDO examinationBatchComSDO = examinationBatchComServices.selectById(li.getCourt2());
					if(examinationBatchComSDO!=null){
						stuSignUpComVo.setCourt(examinationBatchComSDO.getName());
						stuSignUpComVo.setSignUpTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(examinationBatchComSDO.getStartTime())
								+ "-" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(examinationBatchComSDO.getEndTime()));
					}
				}

				list1.add(stuSignUpComVo);
			}

			//导出操作
			EasyPoiUtil.exportExcel(list1, "考生报名信息导出", "考生报名信息导出", DrawLotsVo.class, "考生报名信息导出", response);
		}catch (Exception e){
			e.printStackTrace();
			return result.fail();
		}
		return result.ok();
	}


	@ResponseBody
//	@GetMapping("/list")
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	@RequiresPermissions("jzweb:stuSignUpCom:stuSignUpCom")
	public Result<Page<StuSignUpComDO>> list( StuSignUpComDO stuSignUpComDTO,String current,String number){
		// 查询列表数据
		if (!StringUtils.isBlank(this.getUser().getTrack()) && this.getUser().getTrack().equals("E")){
				//竞赛一级管理员
			stuSignUpComDTO.setCreateId(this.getUserId().toString());
		}else if (!StringUtils.isBlank(this.getUser().getTrack()) && this.getUser().getTrack().equals("D")){
				//工作人员(工作人员在批次表中有一个专门的字段)
			stuSignUpComDTO.setEncipher(this.getUserId().toString());
		}
		Integer placeNum = null;
		if (this.getUser().getPlaceNum()!=null){
			placeNum = this.getUser().getPlaceNum();
		}
		//角色的场次
		Page<StuSignUpComDO> page = stuSignUpComService.ListUstEbSC(Integer.valueOf(current), Integer.valueOf(number), stuSignUpComDTO);
		for (int i = 0; i < page.getRecords().size(); i++) {
			ExaminationBatchComDO examinationBatchComDO=examinationBatchService.selectById(page.getRecords().get(i).getCbatchId());
			ExaminationBatchComSDO examinationBatchComDO1=comSService.selectById(page.getRecords().get(i).getCourt2());
			if(examinationBatchComDO1!=null){
				page.getRecords().get(i).setCourt2(examinationBatchComDO1.getName());
				page.getRecords().get(i).setStartTime(examinationBatchComDO1.getStartTime());
				page.getRecords().get(i).setEndTime(examinationBatchComDO1.getEndTime());
			}
			if(examinationBatchComDO!=null){
				page.getRecords().get(i).setCbatchName(examinationBatchComDO.getName());
			}
			//没有场次 || 场次相同 || 一次加密号为空的时候  这三种情况都不需要隐藏
			if(placeNum==null || page.getRecords().get(i).getPlaceNum() == placeNum  ||
					(stuSignUpComDTO.getPermsType()==1 && page.getRecords().get(i).getRealityNm1()==null) || (stuSignUpComDTO.getPermsType()==2 && page.getRecords().get(i).getRealityNm3()==null)){
				page.getRecords().get(i).setHideOrShow(true);
			}
		}
        return Result.ok(page);
	}
	
	@GetMapping("/add")
	@RequiresPermissions("jzweb:stuSignUpCom:add")
	String add(){

	    return "jzweb/stuSignUpCom/add";
	}


	@GetMapping("/edit/{id}")
	@RequiresPermissions("jzweb:stuSignUpCom:edit")
	String edit(@PathVariable("id") Long id,Model model){
		StuSignUpComDO stuSignUpCom = stuSignUpComService.selectById(id);

		List <ExaminationBatchComSDO> list=comSService.findByKv("cbatch_id",stuSignUpCom.getCbatchId());

		model.addAttribute("list",list);
		model.addAttribute("stuSignUpCom", stuSignUpCom);
		return "jzweb/stuSignUpCom/edit";
	}


	@Log("添加考生报名")
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("jzweb:stuSignUpCom:add")
	public Result<String> save( StuSignUpComDO stuSignUpCom){
		stuSignUpCom.setTypes(stuSignUpCom.getTypes());
		stuSignUpCom.setState(3);
		stuSignUpCom.setSignUpTime(new Date());
		stuSignUpComService.insert(stuSignUpCom);
        return Result.ok();
	}
	/**
	 * 实操赛道录入
	 * @param stuSignUpCom
	 * @return
	 */
	@Log("赛场录入")
	@ResponseBody
	@RequestMapping("/updateEnter")
	public Result<String>  updateEnter( StuSignUpComDO stuSignUpCom){
		StuSignUpComDO stuSignUpComDO1=	stuSignUpComService.selectById(stuSignUpCom.getId());
		String realityNm1 = null;//一次加密
		if(stuSignUpCom.getPermsType()==1){
			realityNm1 = stuSignUpCom.getRealityNm1();
			stuSignUpComDO1.setRealityNm1(realityNm1);
		} else if (stuSignUpCom.getPermsType()==2) {
			realityNm1 = stuSignUpCom.getRealityNm3();
			stuSignUpComDO1.setRealityNm3(realityNm1);
		}
		//只做B赛场一次加密
		if(StringUtil.isNotNull(realityNm1)){
			//首先先查询要修改的一次加密号是否重复
			EntityWrapper<StuSignUpComDO> wrapper = new EntityWrapper<>();
			wrapper.eq("cbatch_id",stuSignUpComDO1.getCbatchId());
			if(stuSignUpCom.getPermsType()==1){
				wrapper.eq("reality_um1",realityNm1);
			} else if (stuSignUpCom.getPermsType()==2) {
				wrapper.eq("reality_um3",realityNm1);
			}
			List<StuSignUpComDO> stuSignUpComDOList = stuSignUpComService.selectList(wrapper);
			for (StuSignUpComDO stuSignUpComDO : stuSignUpComDOList) {
				if(!stuSignUpCom.getId().equals(stuSignUpComDO.getId())){
					return Result.fail("一次加密号不能重复！");
				}
			}
		}
		stuSignUpComDO1.setPlaceNum(this.getUser().getPlaceNum());

		boolean update = stuSignUpComService.updateById(stuSignUpComDO1);
		return update ? Result.ok() : Result.fail();
	}


	@Log("修改考生报名")
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("jzweb:stuSignUpCom:edit")
	public Result<String>  update( StuSignUpComDO stuSignUpCom){
		StuSignUpComDO stuSignUpComDO1=	stuSignUpComService.selectById(stuSignUpCom.getId());
		boolean update = stuSignUpComService.updateById(stuSignUpCom);
		return update ? Result.ok() : Result.fail();
	}
	
	@Log("删除考生报名")
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("jzweb:stuSignUpCom:remove")
	public Result<String>  remove( Long id){
		stuSignUpComService.deleteById(id);
        return Result.ok();
	}
	
	@Log("批量删除考生报名")
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("jzweb:stuSignUpCom:batchRemove")
	public Result<String>  remove(@RequestParam("ids[]") Long[] ids){
		stuSignUpComService.deleteBatchIds(Arrays.asList(ids));
		return Result.ok();
	}


	/**
	 * 导出错误信息
	 *
	 * @param request
	 * @param response
	 * @throws Exception
	 * @author kl
	 */
	@Log("导出错误信息")
	@GetMapping("/importComError")
	@ResponseBody
	@Transactional
	@RequiresPermissions("jzweb:stuSignUpCom:import")
	public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 告诉浏览器用什么软件可以打开此文件
		response.setHeader("content-Type", "application/vnd.ms-excel");
		// 下载文件的默认名称
		response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("考生报名导入错误信息", "UTF-8") + ".xls");
		//编码
		response.setCharacterEncoding("UTF-8");
		String jsonArray = EhCacheUtil.get("stuSignUpComPo" + this.getUserId()).toString();
		JSONArray arrayList = JSONArray.parseArray(jsonArray);
		//转换为目标对象list
		List<ErroeDownVo> groupList = JSONObject.parseArray(arrayList.toJSONString(), ErroeDownVo.class);
		Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), ErroeDownVo.class, groupList);
		workbook.write(response.getOutputStream());
	}


	/**
	 * B（B1、B2）赛场一次加密
	 * @param types
	 * @param model
	 * @return
	 */
	@GetMapping("/num1B")
	@RequiresPermissions("jzweb:stuSignUpCom:stuSignUpComNum1B")
	String StuSignUpComNum1B(Integer types,Integer permsType,Model model){
		model.addAttribute("types",types);
		model.addAttribute("permsType",permsType);
		return "jzweb/stuSignUpCom/stuSignUpComPoNum1B";
	}


	/**
	 * B赛场一次加密导出
	 *
	 * @param response
	 */
	@GetMapping("/downloadImportStuNum1B")
	@RequiresPermissions("jzweb:stuSignUpCom:importNum1B")
	@ResponseBody
	public Result<String> downloadImportTemplateNum1B(HttpServletResponse response,StuSignUpComDO stuSignUpComDTO) {
		Result result = new Result();
		try {
			List<StuSignUpComNum1Vo> list1 = new LinkedList<>();
			Wrapper<StuSignUpComDO> wrapper = new EntityWrapper<StuSignUpComDO>().
					orderBy("comNum", true);
			if(StringUtils.isNotBlank(stuSignUpComDTO.getCbatchName())){
				wrapper.eq("cbatch_id",stuSignUpComDTO.getCbatchName());
			}
	/*		if(StringUtil.notEmpty(stuSignUpComDTO.getCompetitionType())){
				wrapper.addFilter("{0} like CONCAT('%',competition_type,'%')", stuSignUpComDTO.getCompetitionType());
			}*/
			if(StringUtil.notEmpty(stuSignUpComDTO.getIdNumber())){
				wrapper.like("id_number", stuSignUpComDTO.getIdNumber());
			}
			if(StringUtil.notEmpty(stuSignUpComDTO.getName())){
				wrapper.like("name", stuSignUpComDTO.getName());
			}
			wrapper.isNotNull("record_number");
			List<StuSignUpComDO> list=	stuSignUpComService.selectList(wrapper);
			String fileName = "";
			if(stuSignUpComDTO.getPermsType()==1){
				fileName="B1一次加密导出";
			} else if (stuSignUpComDTO.getPermsType()==2) {
				fileName="B2一次加密导出";
			}
			Integer placeNum = this.getUser().getPlaceNum();
			for(StuSignUpComDO li:list){
				StuSignUpComNum1Vo stuSignUpComVo = new StuSignUpComNum1Vo();
				stuSignUpComVo.setRecordNumber(li.getRecordNumber());
				//没有场次 || 场次相同 || 一次加密号为空的时候  这三种情况都不需要隐藏
				if(placeNum==null || li.getPlaceNum() == placeNum  ||
						(stuSignUpComDTO.getPermsType()==1 && li.getRealityNm1()==null) || (stuSignUpComDTO.getPermsType()==2 && li.getRealityNm3()==null)){
					stuSignUpComVo.setNum1("-");
					if (StringUtil.isNotNull(stuSignUpComVo.getNum1())){
						stuSignUpComVo.setNum1(stuSignUpComDTO.getPermsType()==1?li.getRealityNm1():li.getRealityNm3());
					}
				} else {
					stuSignUpComVo.setNum1("*******");
				}
				list1.add(stuSignUpComVo);
			}

			//导出操作
			EasyPoiUtil.exportExcel(list1, fileName, fileName, StuSignUpComNum1Vo.class, fileName, response);
		}catch (Exception e){
			e.printStackTrace();
			return result.fail();
		}
		return result.ok();
	}





}
